package com.white.mybatis.dynamic;

import java.lang.annotation.*;

/**
 * <p>
 * 动态映射
 * </p>
 *
 * @author huangzy
 * @since 2022/2/22
 */
@Target(ElementType.TYPE)
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DynamicMppaer {

    /**
     * Bean名称
     * @return
     */
    String value() default "";

    /**
     * 主表
     * @return
     */
    DynamicTable master();

    /**
     * 一对一关系的从表
     * @return
     */
    DynamicTable[] slave() default {};

    /**
     * 主从表SQL连接构造器
     */
    class SqlBuild {

        /**
         * 构建JOIN连接SQL
         * @return
         */
        public static String buildSql(DynamicMppaer dynamicMppaer){
            DynamicTable master = dynamicMppaer.master();
            DynamicTable[] slave = dynamicMppaer.slave();
            if (slave == null || slave.length == 0) {
                return "";
            }
            StringBuilder sb = new StringBuilder();
            for (DynamicTable dynamicTable : slave) {
                sb.append(dynamicTable.joinType().getSql());
                sb.append(" ");
                sb.append(dynamicTable.value());
                sb.append(" ON ");
                sb.append(master.value());
                sb.append(".");
                sb.append(master.onField());
                sb.append(" = ");
                sb.append(dynamicTable.value());
                sb.append(".");
                sb.append(dynamicTable.onField());
            }
            return sb.toString();
        }
    }
}
